package com.qing.microservices.consul.consumer.api;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import java.util.List;

/**
 * @author guoqf
 * @date 2022/2/11 17:18
 */
@RestController
@Slf4j
public class TestDiscover {

    @Autowired
    private RestTemplate restTemplate;

    @Autowired
    private DiscoveryClient discoveryClient;

    @GetMapping("/test-discovery")
    public String testDiscovery() {
        String serviceId = "consul-producer";
        List<ServiceInstance> instances = discoveryClient.getInstances(serviceId);
        log.info("Found service[{}]' instances[{}]", serviceId, instances);

        ServiceInstance instance = instances.get(0);
        String url = instance.getUri() + "/consul-producer/test";
        log.info("Requested url: {}", url);
        return "request procuder: " + restTemplate.getForObject(url, String.class);
    }
}
